package com.bckj.fastboot.core.extra.retry;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

@Slf4j
@Aspect
public class FastRetryableAspect {

    @Pointcut("@annotation(FastRetryable) && execution(public * *(..))")
    public void pointcut() {
    }

    @Around(value = "pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        Object[] args = joinPoint.getArgs();
        FastRetryable anno = method.getAnnotation(FastRetryable.class);
        if (anno == null || args.length == 0 || !(args[0] instanceof FastRetryParam retryParam)) {
            //不满足条件，直接执行原方法
            return joinPoint.proceed();
        }
        if (retryParam.getRetryCount() > 0) {
            log.info("正在重试中...，retryCount=" + retryParam.getRetryCount());
            return joinPoint.proceed();
        }
        return new FastRetryTemplateBuilder()
                .maxRetryCount(anno.maxRetryCount())
                .initialInterval(anno.initialInterval())
                .multiplier(anno.multiplier())
                .className(joinPoint.getTarget().getClass().getName())
                .methodName(method.getName())
                .args(args)
                .build()
                .execute(() -> {
                    try {
                        return joinPoint.proceed();
                    } catch (Throwable throwable) {
                        throw new RuntimeException(throwable);
                    }
                });
    }
}
